package com.hitqz.robot.camera.netty;

import com.hitqz.robot.camera.util.PelcodCameraToolkit;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
* 编码器
* */
@Slf4j
public class PelcodEncoder extends MessageToByteEncoder<PelcodMessage> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, PelcodMessage message, ByteBuf byteBuf) throws Exception {

            byteBuf.writeBytes(PelcodMessage.header);

            byteBuf.writeBytes(message.getCmd());

            byteBuf.writeBytes(message.getData());

            byteBuf.writeByte(message.getCheck());

            if (log.isDebugEnabled()) {
                byte[] fullMessage = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, fullMessage);
                // 获取远程地址（IP和端口）
                InetSocketAddress remoteAddress = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
                String ip = remoteAddress.getAddress().getHostAddress();
                int port = remoteAddress.getPort();
                log.info("[pelcod] send to [{}:{}]: {} ",ip,port, PelcodCameraToolkit.bytesToHexString(fullMessage));
            }

    }


}
